// 函数组件
import React, { useState, useEffect, useContext } from 'react';
import { Table, Button, Switch, Space, Pagination, ConfigProvider, Select, DatePicker, Modal, PaginationProps, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import createContext from '../../../utils/gyqContext'
import './css/OrderReasonCss/OrderReason.less'
import '../../css/public.less' // 导入公共样式
import zh_CN from 'antd/es/locale/zh_CN';
import { getAllReason, delReason, updateCondition } from '../../../api/OrderApi'
import OrderReasonAdd from './child/OrderReasonAdd';
import OrderReasonDel from './child/OrderReasonDel';
import { ExclamationCircleFilled } from '@ant-design/icons';
const { confirm } = Modal;


//接口
interface DataType {
    key: React.Key;
    appliId: number;
    reasonDescription: string;
    // sort:number;
    startUse: boolean;
    insertTime: string;
    // isEditModalOpen: boolean;
    // clickRow: any;
    // close(): void;

}

function OrderReason() {
    const [data, setData] = useState<DataType[]>()  //所有数据
    const [isModalOpen, setIsModalOpen] = useState(false);      //添加弹框
    const [isEditModalOpen, setIsEditModalOpen] = useState<boolean>(false); //编辑弹框
    const [clickRow, setClickRow] = useState<DataType | null>(null); //点击编辑的那一行数据
    // const [isModalOpen1, setIsModalOpen1] = useState(false);
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);    //多选框
    // const [editValue, setEditValue] = useState<DataType | null>(null)
    const [pageSize, setPageSize] = useState<number>(6) //每页条数
    const [currentPage, setCurrentPage] = useState<number>(1) //当前第几页
    const [pageCount, setPageCount] = useState<number>()  //退换原因条数
    // const [state,setState] = useState<number | boolean>(0)
    const context = useContext<any>(createContext)
    // const [appId,setAppId] = useState<number>()    //获取到删除数据的id
    const onChange = (checked: boolean) => { //点击上架为ture或者false
        console.log('无语',checked);
        // if(checked == true){
        //     setState(1)
        // }else if(checked == false){
        //     setState(0)
        // }
    };
    // console.log('无语真的6',state);
    const shopId = (Items: DataType): void => { //点击上架获取到这一行的数据
        console.log('打印一下',Items.appliId);
        // console.log('判断一下',state);
        let obj = {
            orderId:Items.appliId,
            startUse:Items.startUse?0:1
        }
        console.log('打印了获取你哟',obj);
        //发起修改启用状态请求
        updateCondition([obj]).then(res =>{
            console.log('res成功了',res);
            getAll()
        }).catch(err =>{
            console.log('err失败了',err);
            
        })

        console.log('打印了哟',Items);
    }

    const recommend = (e: boolean | number): void => { //点击首页推荐为ture或者false
        console.log(e);
    };
    const homeId = (Items: DataType): void => { //点击首页推荐获取到这一行的数据
        console.log(Items);
    }

    // const data: DataType[] = [ //模拟的数据都是放在这里的
    //     {
    //         key: '1',
    //         cause: '质量有问题',
    //         grounding: 1,
    //         sort: 1,
    //         date: '2023-2-28',
    //     },
    //     {
    //         key: '2',
    //         cause: '质量有问题',
    //         grounding: 1,
    //         sort: 1,
    //         date: '2023-2-28',
    //     },
    //     {
    //         key: '3',
    //         cause: '质量有问题',
    //         grounding: 1,
    //         sort: 1,
    //         date: '2023-2-28',
    //     },
    //     {
    //         key: '4',
    //         cause: '质量有问题',
    //         grounding: 1,
    //         sort: 1,
    //         date: '2023-2-28',
    //     },
    //     {
    //         key: '5',
    //         cause: '质量有问题',
    //         grounding: 1,
    //         sort: 1,
    //         date: '2023-2-28',
    //     },
    //     {
    //         key: '6',
    //         cause: '质量有问题',
    //         grounding: 1,
    //         sort: 1,
    //         date: '2023-2-28',
    //     },
    // ];
    const columns: ColumnsType<DataType> = [ //表格表头表的类别
        {
            title: '原因描述',
            dataIndex: 'reasonDescription',
            align: 'center',
        },
        {
            title: '排序',
            dataIndex: 'appliId',
            align: 'center',
        },
        {
            title: '是否启用',
            dataIndex: 'startUse',
            align: 'center',
            render: (_, record: DataType) => {
                return ( //这个是加一个选中或者没选中的值defaultChecked
                    <Switch
                        onChange={onChange}
                        defaultChecked={record.startUse}
                        onClick={() => { shopId(record) }}
                    />
                )
            }
        },
        {
            title: '添加时间',
            dataIndex: 'insertTime',
            align: 'center',
        },
        {
            title: '操作',
            dataIndex: 'operation',
            align: 'center',
            render: (_, record) => {
                return ( //这个是加一个选中或者没选中的值defaultChecked
                    <Space size="middle">
                        <button className='edit' onClick={() => editHandle(record)}>编辑</button>
                        <button className='del' onClick={() => { del(record)}}>删除</button>
                    </Space>
                )
            }
        },
    ];

    //组件调用函数
    useEffect(() => {
        console.log('OrderReason组件来咯')
        getAll()
    }, [])


    // 获取所有数据
    const getAll = () => {
        getAllReason({
            pageNum: currentPage,
            size: pageSize
        }).then(res => {
            console.log('res', res);
            setData(res.data.aftereasonList);
            setPageCount(res.data.count)
        }).catch(err => {
            console.log('err错误啦', err);

        })
    }


    // 页码改变
    const pageChange = (page: number, pageSize: number) => {
        setPageSize(pageSize)
        setCurrentPage(page)
        getAllReason({
            pageNum: page,
            size: pageSize,
        }).then(res => {
            setData(res.data.aftereasonList)
            setPageCount(res.data.count)
            // 设置当前页和每页条数
            setPageSize(pageSize)
            setCurrentPage(page)
        }).catch(err => {
            console.log('页码改变出错', err);
            message.error('服务器出错啦')
        })
    }


    //多选框选择按钮
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    //配置多选框
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
        selections: [
            Table.SELECTION_ALL,
            Table.SELECTION_INVERT,
            Table.SELECTION_NONE,
            {
                key: 'odd',
                text: 'Select Odd Row',
                onSelect: (changableRowKeys: any[]) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changableRowKeys.filter((_: any, index: number) => {
                        if (index % 2 !== 0) {
                            return false;
                        }
                        return true;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
            {
                key: 'even',
                text: 'Select Even Row',
                onSelect: (changableRowKeys: any[]) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changableRowKeys.filter((_: any, index: number) => {
                        if (index % 2 !== 0) {
                            return true;
                        }
                        return false;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
        ],
    };
    const hasSelected = selectedRowKeys.length > 0;
    const onShowSizeChange: PaginationProps['onShowSizeChange'] = (current, pageSize) => {
        console.log(current, pageSize);
    };

    //删除一条数据的函数,点击模态框确认删除
    const showPromiseConfirm = (record: any) => {
        confirm({
            title: '确认删除此信息',
            icon: <ExclamationCircleFilled />,
            content: '确认删除这条数据吗?',
            onOk() {
                // 点击确定发起请求
                delReason(
                    [record.appliId]
                ).then(res => {
                    message.success('删除成功！')
                        getAll()
                    // if (res.data.code == 200) {
                    //     message.success('删除成功！')
                    //     getAll()
                    // } else {
                    //     message.info('删除失误啦！')
                    // }
                }).catch(err => {
                    console.log('err错误了哟', err);

                })
            },
        });
    };
    //点击删除按钮，弹出模态框
    const del = (record: any) => {
        console.log('删除的点击事件触发', record);
        showPromiseConfirm(record)
        console.log('点击删除我要执行了哟', record.appliId);

    }

    // 批量删除
    const deltotalHandle = () => {
        confirm({
            title: '提示:',
            icon: <ExclamationCircleFilled />,
            content: '您确定要批量删除这些数据吗？删除后无法恢复！',
            cancelText: '取消',
            okText: '确认',
            onOk() {
                // 点击确定发起请求
                delReason(
                    selectedRowKeys
                ).then(res => {
                    getAll()
                    message.success('删除成功！')
                    // if (res.data.code == 200) {
                    //     getAll()
                    //     message.success('删除成功！')
                    // } else {
                    //     message.info('删除失误啦！')
                    // }
                }).catch(err => {
                    console.log('err', err);
                    message.error('服务器错误哟')
                })
            },
        });
    }

    // 添加弹框
    const add = (): void => {
        console.log('点击了添加');

        setIsModalOpen(true)
    }

    // 关闭添加弹框
    const closeModal = () => {
        setIsModalOpen(false)
    }


    // 编辑
    const editHandle = (record: any) => {
        console.log("我要去编辑信息了", record);
        setIsEditModalOpen(true)
        setClickRow(record)
    }

    // 关闭编辑框
    const closeEdit = (): void => {
        setIsEditModalOpen(false)
    }
    // // 打开编辑弹框并传输数据过去
    // const compile = (item: DataType) => {
    //     setIsModalOpen1(true)
    //     setEditValue(item)
    // }
    // const closeModal1 = () => {
    //     setIsModalOpen1(false)
    // }
    //用户数据


    return (
        <div className='Banner'>
            <createContext.Provider value={ {getAll} }>
                <div className='page-top'>
                    <div className='page-title'>
                        <p>退换货原因设置</p>
                    </div>
                </div>
                <div className='page-context'>
                    <div className='page-table'>
                        <div>
                            <div className='page-div'>
                                <p>数据列表</p>
                                <div>
                                    <button className='add' onClick={add}>添加</button>
                                    <button className='delbtn' onClick={deltotalHandle}>批量删除</button>
                                </div>
                            </div>
                            <ConfigProvider locale={zh_CN}>
                                <Table
                                    rowKey={(item) => item.appliId}
                                    rowSelection={rowSelection}
                                    columns={columns}
                                    dataSource={data}
                                    bordered
                                    scroll={{y:364}}
                                    pagination={{
                                        position: ['bottomCenter'],
                                        total: pageCount,
                                        defaultPageSize: pageSize,
                                        defaultCurrent: currentPage,
                                        pageSizeOptions: [3, 5, 10, 15],
                                        showQuickJumper: true,
                                        showSizeChanger: true,
                                        onChange: pageChange,
                                        showTotal: (pageCount: number) => `共有 ${pageCount} 条数据`
                                    }}
                                />
                            </ConfigProvider>
                        </div>
                    </div>
                </div>
                {/* 这是编辑弹框 */}
                <OrderReasonDel close={closeEdit} isEditModalOpen={isEditModalOpen} clickRow={clickRow}></OrderReasonDel>
                {/* 这是添加弹框 */}
                <OrderReasonAdd isModalOpen={isModalOpen} closeModal={closeModal} ></OrderReasonAdd>
            </createContext.Provider>
        </div >
    )
}

export default OrderReason